//
//  ZGAudioFingerPrintView.m
//  ZGAudioDetective
//
//  Created by 周刚涛 on 2021/9/15.
//

#import "ZGAudioFingerPrintView.h"
#import "ZGAudioFingerPrintTool.h"

@interface ZGAudioFingerPrintView()

@property(nonatomic,strong) NSMutableArray *itemArray;
@property(nonatomic,strong) NSMutableArray *levelArray;
@property(nonatomic,strong) NSArray *filerSamples;
@property(nonatomic,strong) UIColor *itemColor;

@end

@implementation ZGAudioFingerPrintView

//绘制图形
/**
 *下面将根据这个数组进行相关的绘制。
 *数组的数量表示竖条形波纹的数量，数组的元素的大小代表条纹的高度大小。但因为有个别元素会出现过
 *大或过小的问题会对绘制的结果产生辣眼睛的影响，这里对元素进行了一次简单的处理，就是取得数组元素
 *的平均值，超出或不足平均值的元素按照特定的比例进行缩放再与平均值做加或减运算得到要绘制在view上的高度。看代码：
 */
- (void)setupWithRect:(CGRect)rect {
    self.itemArray = [NSMutableArray new];
    ZGAudioFingerPrintTool *tool = ZGAudioFingerPrintTool.alloc.init;
    tool.url = self.url;
    __weak typeof(self)weakSelf = self;
    [tool cutAudioData:self.bounds.size WithBlock:^(id  _Nonnull data) {
        weakSelf.filerSamples = (NSArray*)data;
        
        weakSelf.itemColor = [UIColor colorWithRed:241/255.f green:60/255.f blue:57/255.f alpha:1.0];
        weakSelf.levelArray = [[NSMutableArray alloc] init];
        
        // 计算音轨数组的平均值
        double avg = 0;
        int sum = 0;
        for (int i = 0; i < weakSelf.filerSamples.count; i++) {
            sum += [weakSelf.filerSamples[i] intValue];
        }
        
        avg = sum/weakSelf.filerSamples.count;
        
        for(int i = 0 ; i < weakSelf.filerSamples.count ; i++){
            // 计算每组数据与平均值的差值
            int Xi = [weakSelf.filerSamples[i] intValue];
            CGFloat scale = (Xi - avg)/avg; // 绘制线条的缩放比例
            
            int baseH = 0; // 长度基数,线条长度范围: baseH + 10 ~ baseH + 100

            if (scale <= -0.4) {
                [weakSelf.levelArray addObject:@(baseH + 10)];
            }else if (scale > -0.4 && scale <= -0.3) {
                [weakSelf.levelArray addObject:@(baseH + 20)];
            }else if (scale > -0.3 && scale <= -0.2) {
                [weakSelf.levelArray addObject:@(baseH + 30)];
            }else if (scale > -0.2 && scale <= -0.1) {
                [weakSelf.levelArray addObject:@(baseH + 40)];
            }else if (scale > -0.1 && scale <= 0) {
                [weakSelf.levelArray addObject:@(baseH + 50)];
            }else if (scale > 0 && scale <= 0.1) {
                [weakSelf.levelArray addObject:@(baseH + 60)];
            } else if (scale > 0.1 && scale <= 0.2) {
                [weakSelf.levelArray addObject:@(baseH + 70)];
            } else if (scale > 0.2 && scale <= 0.3) {
                [weakSelf.levelArray addObject:@(baseH + 80)];
            } else if (scale > 0.3 && scale <= 0.4) {
                [weakSelf.levelArray addObject:@(baseH + 90)];
            } else if (scale > 0.4) {
                [weakSelf.levelArray addObject:@(baseH + 100)];
            }
            
            CAShapeLayer *itemline = [CAShapeLayer layer];
            itemline.lineCap       = kCALineCapButt;
            itemline.lineJoin      = kCALineJoinRound;
            itemline.strokeColor   = [[UIColor clearColor] CGColor];
            itemline.fillColor     = [[UIColor clearColor] CGColor];
            [itemline setLineWidth:rect.size.width*0.4/(weakSelf.filerSamples.count)];
            itemline.strokeColor   = [weakSelf.itemColor CGColor];
            
            [weakSelf.layer addSublayer:itemline];
            [weakSelf.itemArray addObject:itemline];
        }
    }];//得到绘制数据
}

- (void)setUrl:(NSURL *)url {
    _url = url;
    [self setupWithRect:self.bounds];
    [self updateItemsWithRect:self.bounds];
}

/**
 此时，self.itemArray中存放的就是需要绘制在view上的线条，下面只需要遍历这些线条，并一一绘制在view上即可。看代码：
 */
- (void)updateItemsWithRect:(CGRect)rect {
    UIGraphicsBeginImageContext(self.frame.size);
    
    CGFloat x = rect.size.width*0.8/(self.filerSamples.count);  // x：表示两个线条的间隔
    CGFloat z = rect.size.width*0.2/self.filerSamples.count;
    CGFloat y = rect.size.width*0.09 - z;  // y：表示线条的起始位置
    
    for(int i=0; i < (self.itemArray.count); i++) {
        UIBezierPath *itemLinePath = [UIBezierPath bezierPath];
        y += x;
        CGPoint point = CGPointMake(y, rect.size.height/2+([[self.levelArray objectAtIndex:i]intValue]+1)*z/2);
        [itemLinePath moveToPoint:point];
        CGPoint toPoint = CGPointMake(y, rect.size.height/2-([[self.levelArray objectAtIndex:i]intValue]+1)*z/2);
        [itemLinePath addLineToPoint:toPoint];
        
        CAShapeLayer *itemLine = [self.itemArray objectAtIndex:i];
        itemLine.path = [itemLinePath CGPath];
    }
    
    UIGraphicsEndImageContext();
}

@end
